import os
import pickle
import threading

# att_met = {port1:method1, port2:method2} ——不变，随程序预设好后只需一次读取，故不设为全局变量
# self_ip = [ipA, ipB]——可以主机自己得到，不设为全局变量
# 目前的全局变量：自身IP/所有节点将要检查的下一漏洞/拓扑结构。定义如下
# order = [[[ipA1, ipA2], next_bug_IDA], [[ipB], next_bug_IDB]]
# order = [[ipA1, next_bug_IDA1], [ipA2, next_bug_IDA2], [ipB, next_bug_IDB]]
# topo = {IPA:[IPB, IPC],IPB:[IPC, IPE];IPD:[IPE]}
# timestamp =
# attacked_ips_list = []
# ip_map = {IPA1: [IPA2, IPA3], IPA2: [IPA1, IPA3], ...} ——只有一个网卡的不加入字典的key


class GlobalVal:
    def __init__(self, valpath):
        self.valpath = valpath
        self.lock = threading.Lock()

    def set_val(self, key, value):
        self.lock.acquire()
        if not os.path.exists(self.valpath):
            pickle.dump({}, open(self.valpath, 'wb'))
        with open(self.valpath, 'rb') as file:
            global_dict = pickle.load(file)
        global_dict[key] = value
        pickle.dump(global_dict, open(self.valpath, 'wb'))
        self.lock.release()

    def get_val(self, key,default=None):
        self.lock.acquire()
        with open(self.valpath, 'rb') as file:
            global_dict = pickle.load(file)
        self.lock.release()
        if key in global_dict.keys():
            return global_dict[key]
        else:
            return str(default)


if __name__ == "__main__":
    # 测试一下
    gv = GlobalVal('./gv_data/GlobalVal.pickle')
    # gv.set_val('key1', 'val1')
    # print(gv.get_val('key1'))

    if not os.path.exists('./gv_data/GlobalVal.pickle'):
        pickle.dump({}, open('./gv_data/GlobalVal.pickle', 'wb'))

    print(gv.get_val("isFirst"))
